package de.le.mfw.server
import com.google.gwt.user.client.rpc.SerializationException

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

trait MailService {

  val fromAdmin = ("magic.for.web@googlemail.com", "Magic-for-Web Admin")

  class Mail(val to: String, val subject: String, val message: String)

  def sendMail(mail: Mail) = {
    val props = new Properties()
    val session = Session.getDefaultInstance(props, null)

    try {
      val msg = new MimeMessage(session)
      msg.setFrom(new InternetAddress(fromAdmin._1, fromAdmin._2))
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.to))
      msg.setSubject("Magic-for-Web: " + mail.subject)
      msg.setText(mail.message)
      Transport.send(msg)

      //TODO später entfernen
      println(mail.message)
    } catch {
      case e: AddressException => throw new SerializationException("Adresse nicht gültig").initCause(e)
      case e: MessagingException => throw new SerializationException("Fehler beim Senden der Nachricht").initCause(e)
      case e => throw new SerializationException(e)
    }
  }
}